package com.sqlcheck.service.impl;

import com.sqlcheck.dto.request.LoginRequest;
import com.sqlcheck.dto.response.LoginResponse;
import com.sqlcheck.dto.response.CurrentUserResponse;
import com.sqlcheck.entity.User;
import com.sqlcheck.repository.UserRepository;
import com.sqlcheck.service.AuthService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Base64;
import java.util.Optional;
import java.util.regex.Pattern;

/**
 * 认证服务实现
 * 简化实现，使用Base64编码作为token，生产环境建议使用JWT
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {

    private final UserRepository userRepository;

    // 工号格式验证：6位数字或K开头+7位数字
    private static final Pattern EMPLOYEE_ID_PATTERN = Pattern.compile("^(\\d{6}|K\\d{7})$", Pattern.CASE_INSENSITIVE);
    
    // 固定密码
    private static final String DEFAULT_PASSWORD = "000000";
    
    // Token前缀
    private static final String TOKEN_PREFIX = "SQLCHECK_";

    @Override
    public LoginResponse login(LoginRequest loginRequest) {
        String employeeId = loginRequest.getEmployeeId();
        String password = loginRequest.getPassword();

        log.info("员工登录尝试: employeeId={}", employeeId);

        // 1. 验证工号格式
        if (!EMPLOYEE_ID_PATTERN.matcher(employeeId).matches()) {
            throw new IllegalArgumentException("工号格式不正确，请输入6位数字工号或K开头+7位数字工号");
        }

        // 2. 验证密码
        if (!DEFAULT_PASSWORD.equals(password)) {
            throw new IllegalArgumentException("密码错误");
        }

        // 3. 查找或创建用户
        User user = findOrCreateUser(employeeId);

        // 4. 生成token
        String token = generateToken(user);

        // 5. 构建响应
        LoginResponse.UserInfo userInfo = LoginResponse.UserInfo.builder()
                .id(user.getId())
                .employeeId(user.getEmployeeId())
                .username(user.getUsername())
                .email(user.getEmail())
                .avatarUrl(user.getAvatarUrl())
                .role(user.getRole())
                .build();

        log.info("员工登录成功: employeeId={}, userId={}", employeeId, user.getId());

        return LoginResponse.builder()
                .token(token)
                .userInfo(userInfo)
                .expiresIn(24 * 60 * 60 * 1000L) // 24小时过期
                .build();
    }

    @Override
    public CurrentUserResponse getCurrentUser(String token) {
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            throw new IllegalArgumentException("无效的访问令牌");
        }

        User user = userRepository.selectById(userId);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }

        return CurrentUserResponse.builder()
                .id(user.getId())
                .employeeId(user.getEmployeeId())
                .username(user.getUsername())
                .email(user.getEmail())
                .avatarUrl(user.getAvatarUrl())
                .isActive(user.getIsActive())
                .role(user.getRole())
                .build();
    }

    @Override
    public boolean validateToken(String token) {
        try {
            return getUserIdFromToken(token) != null;
        } catch (Exception e) {
            log.warn("Token验证失败: {}", e.getMessage());
            return false;
        }
    }

    @Override
    public Long getUserIdFromToken(String token) {
        try {
            if (token == null || !token.startsWith(TOKEN_PREFIX)) {
                return null;
            }

            String encodedData = token.substring(TOKEN_PREFIX.length());
            String decodedData = new String(Base64.getDecoder().decode(encodedData));
            
            // 简单格式: userId:employeeId:timestamp
            String[] parts = decodedData.split(":");
            if (parts.length >= 3) {
                return Long.parseLong(parts[0]);
            }
            
            return null;
        } catch (Exception e) {
            log.warn("解析token失败: {}", e.getMessage());
            return null;
        }
    }

    @Override
    public String generateToken(User user) {
        // 简化实现：Base64编码用户信息
        // 格式: userId:employeeId:timestamp
        String data = user.getId() + ":" + user.getEmployeeId() + ":" + System.currentTimeMillis();
        String encodedData = Base64.getEncoder().encodeToString(data.getBytes());
        return TOKEN_PREFIX + encodedData;
    }

    @Override
    public void logout(String token) {
        // 简化实现：无需特殊处理
        // 生产环境可以维护token黑名单
        log.info("用户退出登录: token前缀={}", token != null ? token.substring(0, Math.min(20, token.length())) + "..." : "null");
    }

    /**
     * 查找或创建用户
     */
    private User findOrCreateUser(String employeeId) {
        Optional<User> existingUser = userRepository.findByEmployeeId(employeeId);
        
        if (existingUser.isPresent()) {
            log.info("找到已存在用户: employeeId={}, userId={}", employeeId, existingUser.get().getId());
            return existingUser.get();
        }

        // 创建新用户
        User newUser = new User();
        newUser.setEmployeeId(employeeId);
        newUser.setPassword(DEFAULT_PASSWORD);
        newUser.setUsername("员工" + employeeId);
        newUser.setEmail(employeeId + "@company.com");
        newUser.setRole(com.sqlcheck.common.enums.UserRole.USER); // 新用户默认为普通用户
        newUser.setIsActive(true);
        newUser.setCreatedAt(LocalDateTime.now());
        newUser.setUpdatedAt(LocalDateTime.now());
        newUser.setDeleted(false);

        userRepository.insert(newUser);
        
        log.info("创建新用户: employeeId={}, userId={}", employeeId, newUser.getId());
        return newUser;
    }
}